#include "epoller.h"

Epoller::Epoller(int maxEvent) : epollFd_(epoll_create(512)), events_(maxEvent)
{
}

Epoller::~Epoller()
{
    close(epollFd_);
}

bool Epoller::AddFd(int fd, uint32_t events)
{
    if(fd < 0) {
        LOG(INFO) << "fd error!";
        return false;
    }
    epoll_event ev = {0};
    ev.data.fd = fd;
    ev.events = events;
    return 0 == epoll_ctl(epollFd_, EPOLL_CTL_ADD, fd, &ev);
}

bool Epoller::DelFd(int fd)
{
    if(fd < 0) return false;
    return 0 == epoll_ctl(epollFd_, EPOLL_CTL_DEL, fd, NULL);
}

bool Epoller::ModFd(int fd, uint32_t events)
{
    if(fd < 0) return false;
    epoll_event ev;
    ev.data.fd = fd;
    ev.events = events;
    
    return 0 == epoll_ctl(epollFd_, EPOLL_CTL_MOD, fd, &ev);
}

int Epoller::Wait(int timeoutMs)
{
    return epoll_wait(epollFd_, &events_[0], static_cast<int>(events_.size()), timeoutMs);
}

int Epoller::GetEventFd(int fd) const
{
    assert(fd >= 0 && fd < events_.size());
    return events_[fd].data.fd;
}

uint32_t Epoller::GetEvents(int fd) const
{
    assert(fd >= 0 && fd < events_.size());
    return events_[fd].events;
}
